package com.freejy.ecommunity.web.controller;

import com.alibaba.fastjson.JSON;
import com.freejy.ecommunity.common.Constants;
import com.freejy.ecommunity.common.Token;
import com.freejy.ecommunity.common.exception.TokenException;
import com.freejy.ecommunity.service.TokenService;
import com.freejy.ecommunity.utils.Result;
import com.freejy.ecommunity.utils.ResultCode;
import com.freejy.ecommunity.utils.StrUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Jerry
 */
public class BaseController 
{
	

	private static final String[] IP_HEADER_CANDIDATES = { 
		"X-Forwarded-For",
		"Proxy-Client-IP",
		"WL-Proxy-Client-IP",
		"HTTP_X_FORWARDED_FOR",
		"HTTP_X_FORWARDED",
		"HTTP_X_CLUSTER_CLIENT_IP",
		"HTTP_CLIENT_IP",
		"HTTP_FORWARDED_FOR",
		"HTTP_FORWARDED",
		"HTTP_VIA",
		"REMOTE_ADDR" };

	@Autowired
	protected HttpServletRequest request;
	
	@Autowired
	protected HttpServletResponse response;
	

    /**
     * get client ip
     * @return
     */
    public String getClientIpAddress() 
    {
		for (String header : IP_HEADER_CANDIDATES) 
		  {
		      String ip = request.getHeader(header);
		      if (StringUtils.isNotBlank(ip) && !"unknown".equalsIgnoreCase(ip)) 
		      {
		          return ip;
		      }
		  }
      return request.getRemoteAddr();
    }
    
    /**
	 * get request token
	 * @return
	 * @throws TokenException
	 */
	@SuppressWarnings("rawtypes")
	public Token getToken() throws TokenException
	{
		Token token = null;
		String authToken = request.getHeader(Constants.XAUTH_TOKEN_HEADER_NAME);
		if (StrUtil.validToken(authToken))
		{
			token = TokenService.getInstance().findToken(authToken);

			if (token == null || !token.getToken().equals(authToken) || TokenService.getInstance().expires(token))
			{
				throw new TokenException(JSON.toJSONString(new Result(ResultCode.TOKEN_INVALID)));
			}
		}
		return token;
	}

	@ModelAttribute("TokenCheck")
	public Token getTokenByRequest() throws TokenException
	{
		return new Token();
		/*Result errDto = null;
		String authToken = request.getHeader(Constants.XAUTH_TOKEN_HEADER_NAME);
		if (StringUtils.isNotBlank(authToken))
		{
			//Token token = TokenService.getInstance().findToken(authToken);
			return new Token();
			if (token != null)
			{
				if (!token.getToken().equals(authToken) || TokenService.getInstance().expires(token))
				{
					errDto = new Result(ResultCode.TOKEN_INVALID);
				} else
				{
					return token;
				}
			} else
			{
				errDto = new Result(ResultCode.TOKEN_INVALID);
			}
		} else
		{
			errDto = new Result(ResultCode.INVALID);
		}
		throw new TokenException(JSON.toJSONString(errDto));
		*/
	}

	public String getUserAgent()
	{
		return request.getHeader("User-Agent");
	}

	public String getOsType()
	{
		String ua = request.getHeader("User-Agent");
		String ostype = null;
		if (ua.contains("iPhone") || ua.contains("ios") || ua.contains("iPad") || ua.contains("iPod"))
		{
			ostype = "ios";
		} else if(ua.contains("android")) {
			ostype = "android";
		} else if(ua.contains("Windows") || ua.contains("Linux") || ua.contains("Mac")) {
			ostype = "pc";
		} else {
			ostype = "other";
		}
		return ostype;
	}
    
    /**
     * return rest success
     * @return
     */
	public <T> ResponseEntity<?> success()
	{
    	return new ResponseEntity<>(new Result<T>(ResultCode.SUCCESS), HttpStatus.OK);
    }

	/**
	 * return rest success
	 * @return
	 */
	public <T> ResponseEntity<?> success(ResultCode rstCode)
	{
		return new ResponseEntity<>(new Result<T>(rstCode), HttpStatus.OK);
	}
    
	/**
	 * return rest success
	 * @param rst
	 * @return
	 */
    public <T> ResponseEntity<?> success(T rst)
    {
    	return new ResponseEntity<>(new Result<T>(rst), HttpStatus.OK);
    }
    
    /**
     * return rest error
     * @param rstCode
     * @return
     */
    public <T> ResponseEntity<?> error(ResultCode rstCode)
    {
    	return new ResponseEntity<>(new Result<T>(rstCode), HttpStatus.BAD_REQUEST);
    }

}
